package com.warmheart.controller.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.controller.BaseController;
import com.warmheart.base.page.PageInfo;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.OperatorUtil;
import com.warmheart.core.util.ParamMapUtil;
import com.warmheart.entity.user.UserRoleMap;
import com.warmheart.service.user.IUserRoleMapService;

/**
 * 
 * @ClassName: UserRoleMapController
 * @Description: 用户角色关联控制器
 * @author ZhangJianyang
 * @date 2025年06月16日 下午13:05:35
 *
 */
@RestController
@RequestMapping("/user/userRoleMap")
public class UserRoleMapController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserRoleMapController.class);

    // 注入用户角色关联service
    @Autowired(required = false)
    private IUserRoleMapService userRoleMapService;

    /**
     * 
     * @Title: listData
     * @Description: 查询用户角色关联列表数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/listData")
    public CommonResult<Map<String, Object>> listData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // 参数对象
        UserRoleMap userRoleMap = new UserRoleMap();
        
        // 每页记录数
        Integer pageSize = ParamMapUtil.getInteger(jsonMap, "pageSize");
        if (pageSize == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "每页记录数不能为空");
        }
        if (pageSize <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "每页记录数必须大于0");
        }
        userRoleMap.setPageSize(pageSize);

        // 页码
        Integer pageId = ParamMapUtil.getInteger(jsonMap, "pageId");
        if (pageId == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "页码不能为空");
        }
        if (pageId <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "页码必须大于0");
        }
        userRoleMap.setPageId(pageId);

        // 查询列表
        PageInfo<UserRoleMap> pageInfo = this.userRoleMapService.queryByList(userRoleMap);

        List<UserRoleMap> dataList = pageInfo.getData();
        Map<String,Object> pageMap = new HashMap<String,Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (dataList != null && dataList.size() > 0) {
            
            // 整理返回数据
            for (UserRoleMap tempData : dataList) {
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("id", tempData.getId());
                tempMap.put("userId", tempData.getUserId());
                tempMap.put("roleId", tempData.getRoleId());
                tempMap.put("cstCreate", tempData.getCstCreate());
                mapList.add(tempMap);
            }
        }
        pageMap.put("dataList", mapList);
        pageMap.put("rowCount", pageInfo.getPager().getRowCount());
        pageMap.put("pageCount", pageInfo.getPager().getPageCount());
        resultMap.put("pageMap", pageMap);
        return CommonResult.success("分页查询用户角色关联数据成功", resultMap);
    }

    /**
     * 
     * @Title: update
     * @Description: 修改用户角色关联数据进入页面
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/update")
    public CommonResult<Map<String, Object>> update(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户角色关联ID不可为空");
        }

        // 校验是否存在
        UserRoleMap checkUserRoleMap = userRoleMapService.queryById(id);
        if (checkUserRoleMap == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户角色关联不存在");
        }
        Map<String, Object> tempMap = new HashMap<String, Object>();
        tempMap.put("id", checkUserRoleMap.getId());
        tempMap.put("userId", checkUserRoleMap.getUserId());
        tempMap.put("roleId", checkUserRoleMap.getRoleId());
        tempMap.put("cstCreate", checkUserRoleMap.getCstCreate());
        resultMap.put("dataMap", tempMap);
        return CommonResult.success("获取用户角色关联数据成功", resultMap);
    }

    /**
     * 
     * @Title: addSave
     * @Description: 添加保存用户角色关联数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @RequestMapping("/addSave")
    public CommonResult<Map<String, Object>> addSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 数据对象
        UserRoleMap userRoleMap = new UserRoleMap();
        
        // 用户ID
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            userRoleMap.setUserId(userId);
        }
        
        // 角色ID
        Integer roleId = ParamMapUtil.getInteger(jsonMap, "roleId");
        if (roleId != null) {
            userRoleMap.setRoleId(roleId);
        }

        try {
            OperatorUtil.addOper(userRoleMap);
            userRoleMapService.add(userRoleMap);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("添加用户角色关联失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "添加用户角色关联失败");
        }

        return CommonResult.success("添加用户角色关联成功");
    }

    /**
     * 
     * @Title: updateSave
     * @Description: 修改保存用户角色关联数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @RequestMapping("/updateSave")
    public CommonResult<Map<String, Object>> updateSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户角色关联ID不可为空");
        }

        // 是否存在校验
        UserRoleMap checkUserRoleMap = userRoleMapService.queryById(id);
        if (checkUserRoleMap == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户角色关联不存在");
        }

        
        // 用户ID
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            checkUserRoleMap.setUserId(userId);
        }
        
        // 角色ID
        Integer roleId = ParamMapUtil.getInteger(jsonMap, "roleId");
        if (roleId != null) {
            checkUserRoleMap.setRoleId(roleId);
        }

        try {
            OperatorUtil.updateOper(checkUserRoleMap);
            userRoleMapService.updateIncludeAll(checkUserRoleMap);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("修改用户角色关联失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "修改用户角色关联失败");
        }

        return CommonResult.success("修改用户角色关联成功");
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除用户角色关联数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @RequestMapping("/delete")
    public CommonResult<Map<String, Object>> delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户角色关联ID不可为空");
        }

        // 是否存在校验
        UserRoleMap checkUserRoleMap = userRoleMapService.queryById(id);
        if (checkUserRoleMap == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户角色关联不存在");
        }

        try {
            userRoleMapService.deleteById(checkUserRoleMap.getId());
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除用户角色关联失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除用户角色关联失败");
        }

        return CommonResult.success("删除用户角色关联成功");
    }
}
